package com.sun.talk.netty

import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import org.springframework.stereotype.Component
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Autowired

@Component
object WebSocketServer {
    // 主从线程组
    private val bossGroup = NioEventLoopGroup()
    private val workGroup = NioEventLoopGroup()
    fun start (){
        try {
            // 创建服务器
            val serverBootstrap = ServerBootstrap()
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel::class.java)
                    .childHandler(WebSocketServerInitializer())
            // 同步开启server 端口号8088
            val channelFuture = serverBootstrap.bind(8088).sync()
            // 同步监听关闭的channel
            channelFuture.channel().closeFuture().sync()
        }finally {
            bossGroup.shutdownGracefully()
            workGroup.shutdownGracefully()
        }
    }
}